package library

import (
	"errors"
	"fmt"
	"golang.org/x/crypto/ssh"
	"log"
	"os"
)

func RunSsh(ip, command string) (string, error) {
	// 建立SSH客户端连接
	client, err := ssh.Dial("tcp", ip+":22", &ssh.ClientConfig{
		User:            "root",
		Auth:            []ssh.AuthMethod{ssh.Password("111111")},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	})
	if err != nil {
		fmt.Println(errors.New("SSH连接失败,IP地址为: " + ip))
		return "", err
	}

	// 建立新会话
	session, err := client.NewSession()
	defer session.Close()
	if err != nil {
		log.Fatalf("new session error: %s", err.Error())
	}

	result, err := session.Output(command)
	if err != nil {
		fmt.Fprintf(os.Stdout, "Failed to run command, Err:%s", err.Error())
		os.Exit(0)
	}
	return string(result), err
}
